﻿@page "/chat"
@rendermode InteractiveServer

@using BlazorWebAppMovies.Services
@inject ChatService ChatService
@implements IDisposable

<div class="chat-container">
    <div class="messages">
        @foreach (var msg in ChatService.Messages)
        {
            <p><strong>@msg.User:</strong> @msg.Message</p>
        }
    </div>
    <input @bind="newMessage"  @bind:event="oninput" @onkeyup="HandleKeyPress" placeholder="输入消息..." />
    <button @onclick="Send">发送</button>
</div>

@code {
    private string? newMessage;
    private string userName = "用户" + Random.Shared.Next(1, 100); // 随机用户名

    protected override void OnInitialized()
    {
        // 订阅消息接收事件
        ChatService.MessageReceived += HandleMessageReceived;
    }

    private async Task HandleKeyPress(KeyboardEventArgs e)
    {
        if (e.Key == "Enter")
        {
            await Send();
        }
    }

    private async Task Send()
    {
        if (!string.IsNullOrEmpty(newMessage))
        {
            await ChatService.SendMessageAsync(userName, newMessage);
            newMessage = string.Empty;
        }
    }

    private void HandleMessageReceived(string user, string message)
    {
        // 收到新消息时强制刷新UI
        InvokeAsync(StateHasChanged);
    }

    public void Dispose()
    {
        // 组件销毁时取消订阅
        ChatService.MessageReceived -= HandleMessageReceived;
    }
}